package 多线程;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            // 模拟任务1
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "Task 1 completed";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            // 模拟任务2
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "Task 2 completed";
        });

        CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2);

        // 等待所有任务完成
        combinedFuture.get();

        System.out.println(future1.isDone());
        System.out.println(future2.isDone());

        // 获取各个任务的结果
        System.out.println(future1.get());
        System.out.println(future2.get());
    }
}
